package com.dragon.stack;

import com.dragon.linkedlist.DummyHeadLinkedList;

/**
 * @author dragon
 * @version 1.0
 * @description
 * @date created in 2018-12-17
 */
public class LinkedListStack<E> implements Stack<E> {

    private DummyHeadLinkedList<E> linkedList;

    public LinkedListStack() {
        linkedList = new DummyHeadLinkedList<>();
    }

    /**
     * 弹栈,将链表最末尾的元素弹出去
     *
     * @return
     */
    @Override
    public E pop() {
        if (linkedList.isEmpty()) {
            throw new IllegalArgumentException("stack is empty");
        }
        return linkedList.remove(size() - 1);
    }

    /**
     * 压栈,将元素添加到链表最尾端
     *
     * @param e
     */
    @Override
    public void push(E e) {
        linkedList.addLast(e);
    }

    /**
     * 获取栈内元素个数
     *
     * @return
     */
    @Override
    public int size() {
        return linkedList.size();
    }

    /**
     * 查看栈顶元素,但是不弹栈
     *
     * @return
     */
    @Override
    public E peek() {
        return linkedList.get(size() - 1);
    }

    /**
     * 判断栈内元素是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return linkedList.size() == 0;
    }

    /**
     * 打印栈内元素
     *
     * @return
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("stack:bottom");
        sb.append(linkedList);
        sb.append("top");
        return sb.toString();
    }
}
